/**
 * Created by arons on 16/7/11.
 */

"use strict";

function timeout(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, ms, 'done');
    });
}

//timeout(2000).then((value) => {
//    console.log(value);
//});

function loadImageAsync(url) {
    return new Promise(function(resolve, reject) {
        var image = new Image();

        image.onload = function() {
            resolve(image);
        };

        image.onerror = function() {
            reject(new Error('Could not load image at ' + url));
        };

        image.src = url;
    });
}

//loadImageAsync("http://n.sinaimg.cn/translate/20160711/_Mdt-fxtwihv0180397.jpg").then((img)=> {
//        console.log(img);
//    }).catch((error) => {
//        console.log("error occurd: ", error);
//    });

var getJSON = function(url) {
    var promise = new Promise(function(resolve, reject){
        var client = new XMLHttpRequest();
        client.open("GET", url);
        client.onreadystatechange = handler;
        client.responseType = "json";
        client.setRequestHeader("Accept", "application/json");
        client.send();

        function handler() {
            if (this.readyState !== 4) {
                return;
            }
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        };
    });

    return promise;
};

//getJSON("/posts.json").then(function(json) {
//    console.log('Contents: ' + json);
//}, function(error) {
//    console.error('出错了', error);
//});


var p1 = new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('fail')), 3000)
})
var p2 = new Promise(function (resolve, reject) {
    setTimeout(() => resolve(p1), 1000)
})
//p2.then(result => console.log(result))
//p2.catch(error => console.log(error))
// Error: fail

var someAsyncThing = function() {
    return new Promise((resolve, reject)=>{
        resolve(xxxx);
    });
}
someAsyncThing().then(()=>{
    console.log("everything is great");
})
//.catch((error)=>{
//    console.log("someAsyncThing execute Error");
//    console.log(error);
//});

// Node.js有一个unhandledRejection事件，专门监听未捕获的reject错误。
//process.on('unhandledRejection', function (err, p) {
//    console.log("unhandledRejection");
//    console.error(err.stack)
//});


// 生成一个Promise对象的数组
var promises = [2, 3, 5, 7, 11, 13].map(function (id) {
    return getJSON("/post/" + id + ".json");
});

Promise.all(promises).then(function (posts) {
    console.log("Promise.all done:", posts);
}).catch(function(reason){
    console.log("Promise.all error:", reason);
});


function test(resolve, reject) {
    var timeOut = Math.random() * 2;
    console.log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            console.log('call resolve()...');
            resolve('200 OK');
        }
        else {
            console.log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}

test(function (value) {
    console.log(value);
}, function (value) {
    console.log(value);
});
